package com.jianbo.proxy.util;

import org.noear.snack.ONode;
import org.noear.snack.core.Feature;
import org.noear.snack.core.Options;

public class Debug {

    private static void myInfo(String info) {
        String str = getStackInfo(5);
        System.out.println("[DEBUG] " + str + " - " + info);
    }

    public static void info(String info) {
        myInfo(info);
    }

    public static void info(String title, String content) {
        String info = getInfo(title, content);
        myInfo(info);
    }

    public static void info(String title, Object obj) {
        String info = getInfo(title, obj);
        myInfo(info);
    }

    public static void info(Object obj) {
        info(getInfo(obj));
    }

    public static String getInfo(String title, String data) {
        String titleStr = "[" + title + "] ";
        return titleStr + data;
    }

    public static String getInfo(String title, Object obj) {
        String titleStr = "[" + title + "] ";
        return titleStr + getInfo(obj);
    }

    public static String getInfo(String data) {
        return data;
    }

    public static String getInfo(Object obj) {
        Options opt = new Options();
        opt.add(Feature.PrettyFormat);
        return ONode.stringify(obj, opt);
    }

    public static String getStackInfo(int level) {
        Info info = getStack(level);
        return info.ClassName + "." 
            + info.MethodName + "(" +  + info.LineNumber + ")";
    }

    public static Info getStack(int level) {
        try {
            StackTraceElement[] stacks = Thread.currentThread().getStackTrace(); 
            StackTraceElement stack = stacks[level];
            Info info = new Info();
            info.ClassName = stack.getClassName();
            info.FileName = stack.getFileName();
            info.LineNumber = stack.getLineNumber();
            info.MethodName = stack.getMethodName();
            return info;
        } catch (Exception e) {
            Info info = new Info();
            info.ClassName = "unknown";
            info.FileName = "unknown";
            info.LineNumber = 0;
            info.MethodName = "unknown";
            return info;
        }
    }

    public static class Info {
        public String ClassName;
        public String FileName;
        public String MethodName;
        public int LineNumber;
    }

    public static void sleep(int i) {
        try {
            Thread.sleep(i);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static String addLineNumber(String code) {
        String[] lines = code.split("\n");
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < lines.length; i++) {
            sb.append((i+1) + " " + lines[i] + "\n");
        }
        return sb.toString();
    }
}
